﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Marbles.Core.Handlers
{
    public class FileSystemIcon : HttpHandlerBase, IHttpHandlerBase
    {
        public void ProcessRequest(HttpContext context)
        {
            Bitmap bmp = null;
            string extn = context.Request.Params["extn"];
            if (string.IsNullOrEmpty(extn)) { extn = ".bin"; }

            if (Marbles.Core.Settings.SettingsManager.TrustLevel == AspNetHostingPermissionLevel.Medium)
            {
                bmp = new Bitmap(32, 32);
                Graphics g = Graphics.FromImage(bmp);
                g.Clear(System.Drawing.Color.White);
            }
            else
            {
                bool shell32 = true;
                Icon ico = null;
                if (shell32)
                {
                    ico = Content.FileSystem.Icons.IconFromExtensionShell(extn, Content.FileSystem.Icons.SystemIconSize.Large);
                }
                else
                {
                    ico = Content.FileSystem.Icons.IconFromExtension(extn, Content.FileSystem.Icons.SystemIconSize.Large);
                }

                if (ico == null)
                {
                    bmp = new Bitmap(32, 32);
                    Graphics g = Graphics.FromImage(bmp);
                }
                else
                {
                    bmp = new Bitmap(ico.Width, ico.Height);
                    Graphics g = Graphics.FromImage(bmp);
                    g.Clear(System.Drawing.Color.White);
                    g.DrawIcon(ico, 0, 0);
                }
            }

            context.Response.ContentType = "image/jpeg";
            context.Response.AddHeader("content-disposition", "inline;filename=" + extn.Replace(".", "") + ".jpg");
            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.Flush();
            context.Response.End();
            bmp.Dispose();
        }

        public string Verbs
        {
            get { return "GET"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "FileSystemIcon.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }

    }
}
